<?php

namespace App\Http\Controllers;

use App\Models\Balance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class BalanceController extends Controller
{
    /**
 * 更新用户余额
 * 
 * @param  \App\Models\User  $user
 * @param  float  $amount
 * @param  string  $flowType  'income' 或 'expense'
 * @param  bool  $isRollback = false 是否为回滚操作
 */
private function updateUserBalance($user, $amount, $flowType, $isRollback = false)
{
    // 计算符号：正常操作与回滚操作符号相反
    $sign = ($isRollback) ? -1 : 1;
    
    DB::transaction(function () use ($user, $amount, $flowType, $sign) {
        // 获取用户余额记录（带锁防止并发）
        $balance = Balance::where('user_id', $user->id)
                         ->lockForUpdate()
                         ->firstOrFail();

        // 根据流向类型处理
        if ($flowType === 'income') {
            $balance->balance += $sign * $amount;
        } else { // expense
            $newBalance = $balance->balance - $sign * $amount;
            
            // 余额不足检查
            if ($newBalance < 0) {
                throw new \Exception('用户余额不足');
            }
            $balance->balance = $newBalance;
        }

        $balance->save();
    });
}
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01'
        ]);
    
    return DB::transaction(function () use ($validated) {
        // 创建账单
        $bill = auth()->user()->bills()->create($validated);
        
        // 加载账单类型流向
        $bill->load('billType:id,flow');
        $flowType = $bill->billType->flow; // 'income' 或 'expense'
        
        // 更新用户余额
        $this->updateUserBalance(auth()->user(), $bill->amount, $flowType);
        
        return response()->json([
            'message' => '账单创建成功'
        ], Response::HTTP_CREATED); // 原有返回
    });
    }

    /**
     * Display the specified resource.
     */
    public function show(Balance $balance)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Balance $balance)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Balance $balance)
    {
        //
    
    
    $validated = $request->validate([
        'amount' => 'required|numeric|min:0.01', // 示例规则
        'bill_type_id' => 'required|exists:bill_types,id',
        // 添加其他必要字段规则
    ]);

    $this->authorize('update', $balance);
    
    return DB::transaction(function () use ($balance, $validated) {
        // 记录原始金额和流向
        $originalAmount = $balance->amount;
        $originalFlow = $balance->billType->flow;
        
        // 更新账单
        $balance->update($validated);
        $balance->refresh()->load('billType:id,flow');
        $newFlow = $balance->billType->flow;
        
        // 金额或流向变化时需要调整余额
        if ($originalAmount != $balance->amount || $originalFlow != $newFlow) {
            // 回滚原金额影响
            $this->updateUserBalance(
                $balance->user, 
                $originalAmount, 
                $originalFlow,
                true // isRollback
            );
            
            // 应用新金额影响
            $this->updateUserBalance(
                $balance->user, 
                $balance->amount, 
                $newFlow
            );
        }
        
        return response()->json([]); // 原有返回
    });

    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Balance $balance)
    {
        //
    }

    /**
     * 获取用户余额
     * 
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBalance()
    {
        $balance = Balance::where('user_id', auth()->id())->first();

        if (!$balance) {
            return response()->json([
                'message' => '用户余额记录不存在'
            ], Response::HTTP_NOT_FOUND);
        }

        return response()->json([
            'balance' => $balance->balance
        ], Response::HTTP_OK);
    }
}
